package com.chunfeng.mypen.config;

import com.chunfeng.mypen.utils.Fastjson2RedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Redis全局配置
 *
 * @author by 春风能解释
 * <p>
 * 2023/11/23
 */
@Configuration
public class RedisConfig {


    /**
     * Redis序列化配置
     *
     * @param redisConnectionFactory 连接工厂
     * @return Redis连接对象
     */
    @Bean
    public RedisTemplate<String, ?> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, ?> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //创建一个json的序列化对象
        Fastjson2RedisSerializer<Object> serializer = new Fastjson2RedisSerializer<>(Object.class);
        //设置value的序列化方式json
        redisTemplate.setValueSerializer(serializer);
        //设置key序列化方式String
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //设置hash key序列化方式String
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        //设置hash value序列化json
        redisTemplate.setHashValueSerializer(serializer);
        // 设置支持事务
        redisTemplate.setEnableTransactionSupport(true);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

}

